﻿// RewriteSrt.cpp: implementation of the CRewriteSrt class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "RewriteSrt.h"
#include "UnicodeText.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CRewriteSrt::CRewriteSrt() {}

CRewriteSrt::~CRewriteSrt() {}

BOOL CRewriteSrt::bRewriteSrt(LPCTSTR lpSrt, CString &csSrtNew, LPCTSTR lpTempFolder, UINT uiCodePage)
{
	CUnicodeText srtold;
	if (!srtold.bReadTextfile(lpSrt, uiCodePage))
		return FALSE;

	//1
	//00:00:20,000 --> 00:00:24,400
	//자막내용
	//이거 찾아 삼만리

	CUnicodeText srtnew;
	srtnew.lLen = srtold.lLen*2;
	srtnew.tcText = new TCHAR[srtnew.lLen];
	ZeroMemory(srtnew.tcText, srtnew.lLen * sizeof(TCHAR));

	long lCount=0;
	TCHAR *tc = srtnew.tcText;
	int pos=0;

	long lTime = lFindTime(srtold.tcText, srtold.lLen, 0);

	while (lTime>=0) {
		_stprintf_s(tc+pos, srtnew.lLen-pos, _T("%d"), ++lCount);
		while (tc[pos]) pos++;
		tc[pos++] = _TCHAR('\r');

		memcpy(tc+pos, srtold.tcText+lTime, 30*sizeof(TCHAR));
		pos+=30;

		lTime+=30;

		//이럴 일은 없지만, 만에 하나 미친 머저리 자막이 있다면...
		while (srtold.tcText[lTime] == _TCHAR('\r')) lTime++;

		long lDblEnter = lFindDblEnter(srtold.tcText, srtold.lLen, lTime);

		int iContentSize = (lDblEnter>=0)?(iContentSize = lDblEnter-lTime):(iContentSize = srtold.lLen-lTime);

		TCHAR *tcBuf = new TCHAR[iContentSize+1];
		memcpy(tcBuf, srtold.tcText+lTime, iContentSize*sizeof(TCHAR));
		tcBuf[iContentSize] = _TCHAR(0);
		CString csBuf(tcBuf);
		delete []tcBuf;

		fix1Sub(csBuf);
		
		iContentSize = csBuf.GetLength();
		memcpy(tc+pos, static_cast<LPCTSTR>(csBuf), iContentSize*sizeof(TCHAR));
		pos+=iContentSize;
		tc[pos++] = _TCHAR('\r');
		tc[pos++] = _TCHAR('\r');

		if (lDblEnter>=0) {
			lTime = lFindTime(srtold.tcText, srtold.lLen, lDblEnter+2);
		} else {
			break;
		}
	}

	srtnew.lLen = pos;

	csSrtNew = lpSrt;

	csSrtNew += _T(".UTF8.srt");
	csSrtNew.Delete(0, csSrtNew.ReverseFind(_TCHAR('\\'))+1);
	csSrtNew = lpTempFolder + csSrtNew;

	if (lCount>0) {
		srtnew.WriteTextfile(csSrtNew);
	}
	return (lCount>0);
}

long CRewriteSrt::lFindTime(TCHAR *tc, long lLen, long lBegin)
{
	long l;
	for (l=lBegin; l<=lLen-30; l++) {
		if (IsTime(tc+l)) return l;
	}
	return -1;
}

BOOL CRewriteSrt::IsTime(TCHAR *tc)
{
	return (
	   _istdigit(tc[0]) &&
	   _istdigit(tc[1]) &&
	   (tc[2] == _TCHAR(':')) &&
	   _istdigit(tc[3]) &&
	   _istdigit(tc[4]) &&
	   (tc[5] == _TCHAR(':')) &&
	   _istdigit(tc[6]) &&
	   _istdigit(tc[7]) &&
	   (tc[8] == _TCHAR(',')) &&
	   _istdigit(tc[9]) &&
	   _istdigit(tc[10]) &&
	   _istdigit(tc[11]) &&
	   (tc[12] == _TCHAR(' ')) &&
	   (tc[13] == _TCHAR('-')) &&
	   (tc[14] == _TCHAR('-')) &&
	   (tc[15] == _TCHAR('>')) &&
	   (tc[16] == _TCHAR(' ')) &&
	   _istdigit(tc[17]) &&
	   _istdigit(tc[18]) &&
	   (tc[19] == _TCHAR(':')) &&
	   _istdigit(tc[20]) &&
	   _istdigit(tc[21]) &&
	   (tc[22] == _TCHAR(':')) &&
	   _istdigit(tc[23]) &&
	   _istdigit(tc[24]) &&
	   (tc[25] == _TCHAR(',')) &&
	   _istdigit(tc[26]) &&
	   _istdigit(tc[27]) &&
	   _istdigit(tc[28]) &&
	   (tc[29] == _TCHAR('\r'))
   );
 }

long CRewriteSrt::lFindDblEnter(TCHAR *tc, long lLen, long lBegin)
{
	while (lBegin<lLen-1) {
		if (
		    (tc[lBegin] == _TCHAR('\r')) &&
		    (tc[lBegin+1] == _TCHAR('\r'))
		)
			return lBegin;

		lBegin++;
	}
	return -1;
}


void CRewriteSrt::fix1Sub(CString &sub)
{
	// 기본 정리
	// 한 줄에 태그나 공백만 있고 내용이 없는 경우 엔터 제거
	int len = sub.GetLength();
	int pos = 0;
	int linebegin = 0;
	bool bContentFound = false;
	CString csSubFixed;
	while (pos<=len) {
		TCHAR now = (pos>=sub.GetLength())?_TCHAR(0):sub.GetAt(pos);
		
		switch (now) {
		case _TCHAR('\r'):
		case _TCHAR(0):
			// 행의 끝 또는 자막의 끝
			// 컨텐츠가 없거나 자막의 끝이면 '\r' 빼고 복사
			csSubFixed += sub.Mid(linebegin, pos-linebegin);
			if (bContentFound && (now != _TCHAR(0))) {
				csSubFixed += _TCHAR('\r');
			}
			if (now == _TCHAR(0)) {
				pos=len+1;
				break;
			} else {
				pos++;
				linebegin = pos;
			}
			break;

		case _TCHAR(' '):
			pos++;
			break;

		case _TCHAR('<'):
			{
				int closePos = sub.Find(_TCHAR('>'), pos);
				if (closePos<0) {
					// 태그가 안 끝나는 등신같은 경우
					// 그냥 맨 끝까지 복사하고 땡침
					csSubFixed += sub.Mid(linebegin);
					break;
				} else {
					pos=closePos+1;
				}
			}
			break;

		default:
			pos++;
			bContentFound = true;
		}

	}
	sub = csSubFixed;
	
	// 혹시나 맨 뒤에 '\r'이 있으면 제거
	sub.TrimRight(_TCHAR('\r'));
}
